package mchecca.controller;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTextField;

import mchecca.model.DecisionLinesEvent;
import mchecca.view.DecisionLinesForm;

/**
 * Class for handling choice textbox GUI events.
 * <p>
 * The {@link ChoiceController} is responsible for doing the following
 * <ul>
 * 	<li>Updating the model when a choice is added/changed</li>
 *  <li>Initiating the beginning of the round</li>
 * <ul>
 * @author Michael Checca
 */
public class ChoiceController implements ActionListener{
	/** {@link DecisionLinesForm} to update */
	DecisionLinesForm dlForm;
	/** {@link DecisionLinesEvent} to update */
	DecisionLinesEvent dlEvent;
	/** Position of the choice box */
	int position;

	/**
	 * Create a new choice controller.
	 * @param dlForm {@link DecisionLinesForm} to control
	 * @param dlEvent {@link DecisionLinesEvent} to control
	 */
	public ChoiceController(int position, DecisionLinesForm dlForm, DecisionLinesEvent dlEvent) {
		this.dlForm = dlForm;
		this.dlEvent = dlEvent;
		this.position = position;
	}

	/** Begins the DecisionLines event.
	 * <p>
	 * Beginning the DecisionLines event causes the following
	 * <ul>
	 * 	<li>Choices are fixed and cannot be renamed</li>
	 * 	<li>Edges may now be drawn by clicking between two lines</li>
	 * </ul>
	 */
	public void beginRound() {
		dlForm.getLinesCanvas().setEnabled(true);
		int edgesRemaining = (dlEvent.getNumChoices() * dlEvent.getNumRounds());
		for (Component c : dlForm.getChoicesPanel().getComponents()) {
			if (c instanceof JTextField)
				((JTextField) c).setEditable(false);
		}
		dlForm.getInformativeMessage().setText(String.format("Edges remaining: %d", edgesRemaining));
	}

	/**
	 * Occurs when the enter key is pressed within the text box.
	 * <p>
	 * This method will check the current input and validate it as a
	 * valid or invalid choice for the {@link DecisionLinesEvent}.
	 * If it is valid, the model is updated.
	 * If it is invalid, the old value is now displayed.
	 * @param e {@link ActionEvent} that initiated the action
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		String choice = ((JTextField) e.getSource()).getText();
		dlEvent.setChoice(position, choice);
		((JTextField) e.getSource()).setText(dlEvent.getChoice(position));
		if (dlEvent.allChoicesValid())
			beginRound();
	}
}
